package com.wits.platform.common.id.generator;
import java.io.Serializable;
import java.util.Properties;

import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.type.IntegerType;
import org.hibernate.type.Type;

import com.wits.platform.common.utils.StringUtil;
  
public class IDGenerator extends TableGenerator{ 
	
	public static final String FORMAT_NAME="sq_format";
	
	public static final String DEF_FORMAT_VALUE=null;
	
	
	public static final String PREFIX_NAME = "sq_prefix";
	
	public static final String DEF_PREFIX_VALUE = "";

	
	private String prefix;
	
	private String format;
	
    @Override  
    public void configure(Type type, Properties params, Dialect dialect)throws MappingException {
    	prefix= ConfigurationHelper.getString(PREFIX_NAME, params, DEF_PREFIX_VALUE);
    	format=ConfigurationHelper.getString(FORMAT_NAME, params, DEF_FORMAT_VALUE);
        super.configure(new IntegerType(), params, dialect);  
    }  

    @Override  
    public synchronized Serializable generate(SessionImplementor session,Object obj) {  
    	Serializable id=super.generate(session, obj);
    	if(StringUtil.isNullOrEmpty(format)){
    		return prefix+id;
    	}
        return prefix+String.format(format,id);
    }  
} 